<template>
  <div class="note-detail-container">
    <div class="note-detail-content">
      <!-- 笔记头部 -->
      <div class="note-header">
        <div class="note-title-section">
          <h1 class="note-title">{{ note.title }}</h1>
          <div class="note-meta">
            <el-tag :type="getStatusType(note.status)" size="small">
              {{ getStatusText(note.status) }}
            </el-tag>
            <span class="note-category" v-if="note.categoryName">
              <el-icon><Folder /></el-icon>
              {{ note.categoryName }}
            </span>
            <span class="note-time">
              <el-icon><Clock /></el-icon>
              {{ formatTime(note.updateTime) }}
            </span>
            <span class="note-words">
              <el-icon><Document /></el-icon>
              {{ note.wordCount || 0 }} 字
            </span>
          </div>
        </div>
        
        <div class="note-actions">
          <el-button type="primary" icon="Edit" @click="editNote">
            编辑
          </el-button>
          <el-button icon="Share" @click="shareNote">
            分享
          </el-button>
          <el-dropdown @command="handleCommand">
            <el-button icon="More">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="export">导出</el-dropdown-item>
                <el-dropdown-item command="copy">复制链接</el-dropdown-item>
                <el-dropdown-item command="favorite">
                  {{ note.isFavorite ? '取消收藏' : '收藏' }}
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 笔记内容 -->
      <div class="note-content">
        <el-card>
          <div class="content-body" v-html="note.content"></div>
        </el-card>
      </div>

      <!-- 笔记标签 -->
      <div class="note-tags" v-if="note.tags && note.tags.length">
        <el-card>
          <template #header>
            <span>标签</span>
          </template>
          <div class="tags-list">
            <el-tag 
              v-for="tag in note.tags"
              :key="tag"
              type="info"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-card>
      </div>

      <!-- 笔记附件 -->
      <div class="note-attachments" v-if="note.attachments && note.attachments.length">
        <el-card>
          <template #header>
            <span>附件</span>
          </template>
          <div class="attachments-list">
            <div 
              v-for="attachment in note.attachments"
              :key="attachment.id"
              class="attachment-item"
              @click="downloadAttachment(attachment)"
            >
              <el-icon class="attachment-icon">
                <component :is="getFileIcon(attachment.type)" />
              </el-icon>
              <div class="attachment-info">
                <div class="attachment-name">{{ attachment.name }}</div>
                <div class="attachment-size">{{ formatFileSize(attachment.size) }}</div>
              </div>
              <el-button type="text" icon="Download">下载</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 相关笔记 -->
      <div class="related-notes" v-if="relatedNotes.length">
        <el-card>
          <template #header>
            <span>相关笔记</span>
          </template>
          <div class="related-notes-list">
            <div 
              v-for="relatedNote in relatedNotes"
              :key="relatedNote.id"
              class="related-note-item"
              @click="goToNote(relatedNote.id)"
            >
              <div class="related-note-info">
                <h4 class="related-note-title">{{ relatedNote.title }}</h4>
                <p class="related-note-summary">{{ relatedNote.summary }}</p>
                <div class="related-note-meta">
                  <span class="related-note-time">{{ formatTime(relatedNote.updateTime) }}</span>
                  <span class="related-note-category" v-if="relatedNote.categoryName">
                    {{ relatedNote.categoryName }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 版本历史 -->
      <div class="note-versions" v-if="versions.length">
        <el-card>
          <template #header>
            <div class="versions-header">
              <span>版本历史</span>
              <el-button type="text" @click="showAllVersions">查看全部</el-button>
            </div>
          </template>
          <div class="versions-list">
            <div 
              v-for="version in versions.slice(0, 5)"
              :key="version.id"
              class="version-item"
            >
              <div class="version-info">
                <div class="version-title">{{ version.title }}</div>
                <div class="version-time">{{ formatTime(version.createTime) }}</div>
              </div>
              <div class="version-actions">
                <el-button type="text" @click="viewVersion(version)">查看</el-button>
                <el-button type="text" @click="restoreVersion(version)">恢复</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getNoteDetail,
  getRelatedNotes,
  getNoteVersions,
  deleteNote,
  favoriteNote,
  unfavoriteNote,
  exportNote
} from '@/api/note'

const route = useRoute()
const router = useRouter()

// 响应式数据
const note = ref({})
const relatedNotes = ref([])
const versions = ref([])

// 获取笔记详情
const loadNoteDetail = async () => {
  try {
    const response = await getNoteDetail(route.params.id)
    if (response.code === 200) {
      note.value = response.data
      loadRelatedNotes()
      loadVersions()
    } else {
      ElMessage.error('获取笔记详情失败')
    }
  } catch (error) {
    console.error('获取笔记详情失败:', error)
    ElMessage.error('获取笔记详情失败')
  }
}

// 获取相关笔记
const loadRelatedNotes = async () => {
  try {
    const response = await getRelatedNotes(note.value.id)
    if (response.code === 200) {
      relatedNotes.value = response.data || []
    }
  } catch (error) {
    console.error('获取相关笔记失败:', error)
  }
}

// 获取版本历史
const loadVersions = async () => {
  try {
    const response = await getNoteVersions(note.value.id)
    if (response.code === 200) {
      versions.value = response.data || []
    }
  } catch (error) {
    console.error('获取版本历史失败:', error)
  }
}

// 编辑笔记
const editNote = () => {
  router.push(`/note/${note.value.id}/edit`)
}

// 分享笔记
const shareNote = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  switch (command) {
    case 'export':
      await exportNoteFile()
      break
    case 'copy':
      shareNote()
      break
    case 'favorite':
      await toggleFavorite()
      break
    case 'delete':
      await deleteNoteConfirm()
      break
  }
}

// 导出笔记
const exportNoteFile = async () => {
  try {
    await exportNote(note.value.id)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 切换收藏
const toggleFavorite = async () => {
  try {
    if (note.value.isFavorite) {
      await unfavoriteNote(note.value.id)
      note.value.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteNote(note.value.id)
      note.value.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除笔记
const deleteNoteConfirm = async () => {
  try {
    await ElMessageBox.confirm(`确认要删除笔记《${note.value.title}》吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteNote(note.value.id)
    ElMessage.success('删除成功')
    router.push('/note')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 下载附件
const downloadAttachment = (attachment) => {
  // 创建下载链接
  const link = document.createElement('a')
  link.href = attachment.url
  link.download = attachment.name
  link.click()
}

// 跳转到其他笔记
const goToNote = (noteId) => {
  router.push(`/note/${noteId}`)
}

// 查看所有版本
const showAllVersions = () => {
  router.push(`/note/${note.value.id}/versions`)
}

// 查看版本
const viewVersion = (version) => {
  router.push(`/note/${note.value.id}/version/${version.id}`)
}

// 恢复版本
const restoreVersion = async (version) => {
  try {
    await ElMessageBox.confirm(`确认要恢复到版本 ${version.title} 吗？`, '确认恢复', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用恢复版本的API
    ElMessage.success('版本恢复成功')
    loadNoteDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复版本失败:', error)
      ElMessage.error('恢复版本失败')
    }
  }
}

// 工具函数
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(1)} ${units[index]}`
}

const getStatusType = (status) => {
  const typeMap = {
    'DRAFT': 'info',
    'PUBLISHED': 'success',
    'ARCHIVED': 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'ARCHIVED': '已归档'
  }
  return textMap[status] || status
}

const getFileIcon = (type) => {
  const iconMap = {
    'image': 'Picture',
    'document': 'Document',
    'video': 'VideoPlay',
    'audio': 'Headphones',
    'archive': 'Box'
  }
  return iconMap[type] || 'Document'
}

// 页面加载
onMounted(() => {
  loadNoteDetail()
})
</script>

<style lang="scss" scoped>
.note-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.note-detail-content {
  max-width: 1000px;
  margin: 0 auto;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .note-title-section {
    flex: 1;
    
    .note-title {
      font-size: 28px;
      font-weight: 600;
      margin: 0 0 16px 0;
      color: #303133;
    }
    
    .note-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      flex-wrap: wrap;
      
      .note-category,
      .note-time,
      .note-words {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #606266;
        font-size: 14px;
      }
    }
  }
  
  .note-actions {
    display: flex;
    gap: 8px;
  }
}

.note-content {
  margin-bottom: 20px;
  
  .content-body {
    min-height: 400px;
    line-height: 1.8;
    font-size: 16px;
    color: #303133;
    
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: 20px 0 10px 0;
      color: #303133;
    }
    
    :deep(p) {
      margin: 12px 0;
    }
    
    :deep(img) {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
    }
    
    :deep(code) {
      background-color: #f5f5f5;
      padding: 2px 4px;
      border-radius: 3px;
      font-family: 'Monaco', 'Consolas', monospace;
    }
    
    :deep(pre) {
      background-color: #f5f5f5;
      padding: 16px;
      border-radius: 4px;
      overflow-x: auto;
    }
  }
}

.note-tags,
.note-attachments,
.related-notes,
.note-versions {
  margin-bottom: 20px;
  
  .tags-list {
    .tag-item {
      margin: 0 8px 8px 0;
    }
  }
  
  .attachments-list {
    .attachment-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        background-color: #f8f9fa;
      }
      
      .attachment-icon {
        font-size: 24px;
        color: #409eff;
      }
      
      .attachment-info {
        flex: 1;
        
        .attachment-name {
          font-weight: 500;
          color: #303133;
        }
        
        .attachment-size {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
  
  .related-notes-list {
    .related-note-item {
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        background-color: #f8f9fa;
      }
      
      .related-note-title {
        margin: 0 0 8px 0;
        font-size: 16px;
        font-weight: 500;
        color: #409eff;
      }
      
      .related-note-summary {
        margin: 0 0 8px 0;
        color: #606266;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .related-note-meta {
        display: flex;
        gap: 12px;
        
        .related-note-time,
        .related-note-category {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
  
  .versions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .versions-list {
    .version-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .version-info {
        .version-title {
          font-weight: 500;
          color: #303133;
        }
        
        .version-time {
          color: #909399;
          font-size: 12px;
        }
      }
      
      .version-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
}

@media (max-width: 768px) {
  .note-detail-container {
    padding: 10px;
  }
  
  .note-header {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
    
    .note-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .note-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
